package com.tanhua.dubbo.api;

import cn.hutool.core.collection.CollectionUtil;
import com.mongodb.client.result.UpdateResult;
import com.tanhua.dubbo.api.db.UserInfoApi;
import com.tanhua.dubbo.api.mongo.MovementApi;
import com.tanhua.dubbo.config.MongoAsyncService;
import com.tanhua.dubbo.utils.IdWorker;
import com.tanhua.model.enums.CommentType;
import com.tanhua.model.mongo.Comment;
import com.tanhua.model.mongo.Friend;
import com.tanhua.model.mongo.Movement;
import com.tanhua.model.vo.MovementVo;
import com.tanhua.model.vo.PageResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.bson.types.ObjectId;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@DubboService
@Slf4j
public class MovementApiImpl implements MovementApi {

    @Autowired
    private MongoTemplate mongoTemplate;


    @Autowired
    private MongoAsyncService mongoAsyncService;



    @Autowired
    private IdWorker idWorker;

    /**
     *  发布动态
     */
    @Override
    public Movement post(Movement movement) {
        long timeMillis = System.currentTimeMillis();
        movement.setPid(idWorker.getNextId("movement"));
        movement.setCreated(timeMillis);
        Movement movement1 = mongoTemplate.insert(movement);
        ObjectId id = movement.getId();
        Query query = new Query();
        query.addCriteria(Criteria.where("userId").is(movement.getUserId()));
        List<Friend> friends = mongoTemplate.find(query, Friend.class);
        mongoAsyncService.MovementThread(friends,id,timeMillis,movement);
        log.error("主线程调用完成");
        return movement1;
    }

    /**
     *  获取动态
     * @param friendList
     * @param page
     * @return
     */
    @Override
    public PageResult<Movement> getMovement(List<Friend> friendList,PageResult page) {
        Long count = 0l;
        List<Movement> voList = new ArrayList<>();
        for (Friend friend : friendList) {

            Query query = new Query();
            query.addCriteria(Criteria.where("userId").is(friend.getFriendId()));
            query.skip((page.getPage()-1)* page.getPagesize()).limit(Math.toIntExact(page.getPagesize()));
            List<Movement> movements = mongoTemplate.find(query, Movement.class);
            for (Movement movement : movements) {
                voList.add(movement);
            }
            query = new Query(Criteria.where("userId").is(friend.getFriendId()));
            count += mongoTemplate.count(query, Movement.class);
        }

        return new PageResult<>(page.getPage(), page.getPagesize(), count,voList);
    }

    /**
     * 获取好友
     * @param userId
     * @return
     */
    @Override
    public List<Friend> getFriend(Long userId) {
        Query query = new Query();
        query.addCriteria(Criteria.where("userId").is(userId));
        List<Friend> friends = mongoTemplate.find(query, Friend.class);
        return friends;
    }

    /**
     * 获取推荐动态
     * @param pageResult
     * @return
     */
    @Override
    public PageResult<Movement> getRecommend(PageResult pageResult,List<String> ids) {

        if (CollectionUtil.isNotEmpty(ids)){

            List<Movement> movements = new ArrayList<>();
            for (String id : ids) {
                Query query = new Query().addCriteria(Criteria.where("pid").is(Long.parseLong(id)));
                Movement movement = mongoTemplate.findOne(query, Movement.class);
                movements.add(movement);
            }
            return new PageResult<>(pageResult.getPage(), pageResult.getPagesize(), 0L,movements);
        }
        Query query = new Query();
        query.skip((pageResult.getPage() - 1) * pageResult.getPagesize()).limit(Math.toIntExact(pageResult.getPagesize()));
        query.with(Sort.by("created").descending());
        long count = mongoTemplate.count(query, Movement.class);
        List<Movement> movements = mongoTemplate.find(query, Movement.class);

        return new PageResult<Movement>(pageResult.getPage(), pageResult.getPagesize(), count,movements);
    }
    /**
     * 喜欢动态
     * @param id
     *
     */
    @Override
    public Integer loveMovement(ObjectId id,Long loginId) {
        Query query = new Query(Criteria.where("_id").is(id));
        Update update = new Update();
        mongoTemplate.updateFirst(query, update.inc("loveCount",1), Movement.class);
        Movement movement = mongoTemplate.findOne(query, Movement.class);
        Comment init = Comment.init(CommentType.LOVE.getType(), loginId, movement.getUserId(), id);
        mongoTemplate.insert(init, "comment");

        return movement.getLoveCount();
    }

    /**
     * 取消喜欢
     *
     */
    @Override
    public Integer unloveMovement(ObjectId id,Long loginId) {
        Query query = new Query(Criteria.where("_id").is(id));
        Update update = new Update();
        mongoTemplate.updateFirst(query, update.inc("loveCount",-1), Movement.class);
        Movement one = mongoTemplate.findOne(query, Movement.class);
        Query query1 = new Query(Criteria.where("publishId").is(id).and("commentType").is(CommentType.LOVE.getType()).and("userId").is(loginId));
        mongoTemplate.remove(query1,Comment.class);
        return one.getLoveCount() ;
    }

    /**
     * 点赞动态
     * @param id
     */
    @Override
    public Integer likeMovement(ObjectId id,Long loginId) {
        Query query = new Query(Criteria.where("_id").is(id));
        Update update = new Update();
        mongoTemplate.updateFirst(query, update.inc("likeCount",1), Movement.class);
        Movement one = mongoTemplate.findOne(query, Movement.class);
        Comment init = Comment.init(CommentType.LIKE.getType(), loginId, one.getUserId(), id);
        Comment comment = mongoTemplate.insert(init, "comment");
        return one.getLikeCount();

    }
    /**
     * 取消点赞
     *
     */
    @Override
    public Integer dislike(ObjectId id,Long loginId) {
        Query query = new Query(Criteria.where("_id").is(id));
        Update update = new Update();
        mongoTemplate.updateFirst(query, update.inc("likeCount",-1), Movement.class);
        Movement one = mongoTemplate.findOne(query, Movement.class);
        Query query1 = new Query(Criteria.where("publishId").is(id).and("commentType").is(CommentType.LIKE.getType()).and("userId").is(loginId));
        mongoTemplate.remove(query1,Comment.class);
        return one.getLikeCount();
    }

    /**
     * 获取用户动态
     * @param pageResult
     * @param id
     * @return
     */
    @Override
    public PageResult<Movement> getAllMovement(PageResult pageResult, Long id) {
        Query query = new Query(Criteria.where("userId").is(id));
        long count = mongoTemplate.count(query, Movement.class);
        if (count > 10) {
            query.skip((pageResult.getPage() - 1) * pageResult.getPagesize()).limit(Math.toIntExact(pageResult.getPagesize()));
        }
        query.with(Sort.by("created").descending());
        List<Movement> movements = mongoTemplate.find(query, Movement.class);

        return new PageResult<Movement>(pageResult.getPage(), pageResult.getPagesize(), count,movements);
    }
    /**
     *     获取单个动态
     * @param id
     * @return
     */
    @Override
    public Movement getOneMovement(ObjectId id) {
        Query query = new Query().addCriteria(Criteria.where("_id").is(id));
        Movement one = mongoTemplate.findOne(query, Movement.class);
        return one;
    }


}
